import { Ref, ref } from 'vue'
import { cloneDeep } from 'lodash'

interface UseDialogParams {
  formRef?: Ref<any>
  props?: any
  form?: any
  beforeOpenFunction?: () => void
  beforeCloseFunction?: () => void
}

export default function useDialog({
  formRef = ref(null),
  props = null,
  form = null,
  beforeOpenFunction,
  beforeCloseFunction
}: UseDialogParams) {
  const isShow = ref(false)
  const formData = ref<any>(form)
  function cancel() {
    isShow.value = false
  }
  async function open() {
    isShow.value = true
  }
  function handleOpen() {
    if (props.modalType === 'edit') {
      formData.value = cloneDeep(props.modalData)
    } else {
      formData.value = cloneDeep(form)
    }
    beforeOpenFunction && beforeOpenFunction()
  }
  function handleClose() {
    beforeCloseFunction && beforeCloseFunction()
    if (!formRef.value) return
    formRef.value.resetFields()
  }
  return {
    formData,
    cancel,
    open,
    isShow,
    handleClose,
    handleOpen
  }
}
